const utils = require('../../../utils/util.js')
import Toast from '../../../vant-weapp/dist/toast/toast'
//测试使用 修改的参数
const testDataType = 1

import { productList, giveorCancelike, operInformation, browsingVolume, designId, getRecommend} from '../../../config/config.js'
//index.js
//获取应用实例
const app = getApp()
Page({
  data: {
    capBarMoveFlag:false,
    hasUserInfo: false,
    screenHeight: app.globalData.screenHeight,
    boundButtonRect:{   },
    // 点赞数量
    likeCountStr : 0,
    likeCount : 0,
    isCollect:1,
    isLike:1,
    listData: [],
    designId: '',
    type: '',
    dataShow: false,
    options:{},
    pictureIndex: 1,
    content: '',
    isIphoneX: app.globalData.isIphoneX,
    userInfo: ''
  },

  onLoad: function (options) {
    this.getBoundButtonRect()
    this.getPostNavHeight()

    const currOpenId = wx.getStorageSync('openId')

    this.data.openId = currOpenId
    // 获取用户信息
    this.getLocalUserInfo()

     wx.showShareMenu({
      // 要求小程序返回分享目标信息
      withShareTicket: true
    }); 

    const { type = 1, id} = options
    this.ordersCount(id, type, false)
    this.setData({
      designId: id
    })
  },

  getPostNavHeight:function(){
    utils.getFrameById('#poster-nav', (frame) => {
      if (frame && frame.height) {
        this.setData({
          posterNavHeight: frame.height
        })
      }
    })
    utils.getFrameById('#poster-tab-box', (frame) => {
      if (frame && frame.height) {
        this.setData({
          posterTabBoxH: frame.height
        })
      }
    })
  },
  
  getBoundButtonRect:function(){
    let data = wx.getMenuButtonBoundingClientRect()
    const screenWidth =  app.globalData.screenWidth 
    let left = screenWidth - data.right
    let top = data.top
    let height = data.height
    let width = data.width
    this.setData(
      {
         boundButtonRect: {
           left,
           height,
           top,
           width
         }
      }
    )
  },

//获取详情数据
  ordersCount(designId, hideTip) {
    const userId = wx.getStorageSync('openId') || ''
    let that = this
    let params = {
      openId: userId
    }
    utils.$http(app.globalData.api.GetCmsContentInformation+designId, params,'POST',false,'JSON').then(res => {
      if (res.success == 1) {
        let rst = res.data
        let content = rst.content
        content = content.replace(/;\s*width\s*:\s*/g, ';max-width:100%;');
        content = content.replace(/<img[^>]*>/gi, (match, capture) => {
          return match.replace(/style\s*?=\s*?([‘"])[\s\S]*?\1/ig, 'style="max-width:100%!important;height:auto;display:block"') // 替换style
        })
        content =  content.replace(/<img/gi, '<img style="width:100%;height:auto;display:block;" '),

        that.setData({
          listData: rst,
          content: content,
          dataShow: true,
          likeCount: rst.thumbsUpNum,
          likeCountStr: rst.thumbsUpNumStr,
          isLike: rst.isThumbsUp ? 1 : 0,// true 已点赞 false 未点赞
          isCollect:rst.isCollection ? 1 : 0 // true 已收藏 false 未收藏
        })
      } else {
        utils.globalShowTip(false)
          wx.showModal({
          title: '温馨提示',
          content: res.msg,
          success(res) {}
        })
      }
      utils.globalShowTip(false)
    }).catch(res => {
      utils.globalShowTip(false)
    })
  },

  toLoginPage() {
    let message = ''
    if(!this.data.userInfo) {
      message = '未登陆，是否跳到登陆页登陆'
    } 
    const designId = this.data.designId
    wx.showModal({
      title: '提示',
      content: message,
      success:function(res) {
        if(res.confirm){
          wx.navigateTo({
            url: '/pages/mine/register/index'
          });
        }
      }
    })
  },
  /**
   * 获取本地用户信息
  */
   getLocalUserInfo: function(){
    const userInfo = wx.getStorageSync('userInfo')
    if (userInfo){
      this.setData({ userInfo, phone: userInfo.phone })
    }
  },
  // 收藏
  handleCollect:function() {
    const userInfo =  wx.getStorageSync("userInfo")
    const phone = wx.getStorageSync('phone')

    if(userInfo && phone) {
      const userId =  wx.getStorageSync("openId") || ''
      const params = {
        userId: userId,
        articleId: this.data.listData.id,
        type: this.data.isCollect === 0 ? 1 : 2
      }
      utils.$http(app.globalData.api.SetArticleCollectOrCancel, params, 'POST', false, 'JSON').then(({success ,data}) => {
        if(success === 1){
          const msg = this.data.isCollect === 0 ? '收藏成功' : '取消收藏成功'
          wx.showToast({
            title: msg,
            type:'success'
          })
          this.setData({
            isCollect: this.data.isCollect === 0 ? 1 : 0
          })
        }
      })
    } else {
      this.toLoginPage() 
    }
  },
  
  // 点赞
  handleDianZan:function() {
    const userInfo =  wx.getStorageSync("userInfo")
    const phone = wx.getStorageSync('phone')

    if(userInfo && phone) {
      const userId = wx.getStorageSync("openId") || ''
      const params = {
        userId: userId,
        articleId: this.data.listData.id,
        type: this.data.isLike === 0 ? 1 : 2, //isLike 0 未点赞 1 点赞  type 1 点赞 2 取消点赞
        thumbsUpNum: this.data.isLike === 0 ? this.data.likeCount + 1 : this.data.likeCount - 1 
      }
      utils.$http(app.globalData.api.SetArticleGiveOrCancelLike, params, 'POST', false, 'JSON').then(({success,data}) => {
        if (success === 1){
          const msg = this.data.isLike === 0 ? '点赞成功' : '取消点赞成功'
          wx.showToast({
            title: msg,
            type: 'success'
          })

          const likeCount = this.data.isLike === 0 ? (parseInt(this.data.likeCount) + 1) : (parseInt(this.data.likeCount) - 1)
          this.setData({
            likeCount: likeCount < 0 ? 0 : data.thumbsUpNum,
            isLike: this.data.isLike === 0 ? 1 : 0,
            likeCountStr: likeCount < 0 ? 0 : data.thumbsUpNumStr,
          })
        }
      })
    } else {
      this.toLoginPage() 
    }
  },

  // 获取当前轮播图的index
  onSlideChangeEnd: function (e) {
    var that = this;
    that.setData({
      pictureIndex: e.detail.current + 1
    })
  },
  goBack:function(){
    const currentPages = getCurrentPages()
    if (currentPages.length <= 1){
       wx.switchTab({
         url: '/pages/home/main/index',
       })
    }  else {
      wx.navigateBack({
        delta: 1,
        success: function (e) {
          const page = getCurrentPages().pop();
          if (page == undefined || page == null) return;
          page.onLoad();
         }
      })
    }
  
  },

  onPageScroll(e){
    const isSatisfy = e.scrollTop  >= 100  // 高度大于100的时候 显示白底标签栏
    if(this.data.capBarMoveFlag == isSatisfy) { 
      return false;
    } else {
      this.setData({
        capBarMoveFlag: isSatisfy
      })
    }
  },
  goHome:function(){
    wx.switchTab({
      url: '/pages/home/main/index'
    })
  },
   
  sharingBindings: function (sharerOpenId, sharerPhone){
    const lookerOpenId = wx.getStorageSync('openId')
    const params = {
      sharingPeopleMpOpenid: sharerOpenId,
      sharingPeoplePhone: sharerPhone,
      sharedPeopleMpOpenid: lookerOpenId,
      caseId: this.data.designId,
      caseName: this.data.listData.mhName
    }
    utils.$http(app.globalData.api.SharingBindings, params,"POST",false,"JSON").then((res)=>{
   

    })
  },

  getShareTitle:function(){

  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    const userInfo =  wx.getStorageSync("userInfo")
    const phone = wx.getStorageSync('phone')

    if(userInfo && phone) {
      const _this = this
      const sharerPhone = wx.getStorageSync('phone') || ''
      const sharerOpenId = wx.getStorageSync('openId') 

      const picturePath = this.data.listData.pictureList.length ? utils.filterURL(this.data.listData.pictureList[0].picturePath, 'market') : ''
      if (res.from === 'button') {
        // 来自页面内转发按钮
        return {
          title: this.data.listData.name || '详情页',
          imageUrl: utils.filterURL(picturePath),
          path: "pages/guide/index/index?id=" + this.data.listData.id + "&sharerPhone=" + sharerPhone + "&sharerOpenId=" + sharerOpenId,
        }
      }
      return {
        title: this.data.listData.name || '详情页',
        imageUrl:  utils.filterURL(picturePath),
        path: "pages/guide/index/index?id=" + this.data.listData.id + "&sharerPhone=" + sharerPhone + "&sharerOpenId=" + sharerOpenId,
      }
    } else {
      wx.hideShareMenu()
    }
  },

  onShow() {

  }
})
